package com.th.therp.interceptor;
import com.th.therp.context.BaseContext;
import com.th.therp.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 实现了 HandlerInterceptor 接口，用于在每次 HTTP 请求到达处理器之前对请求进行拦截和验证
 */
@Log4j2
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    //preHandle类在请求处理器之前被调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            log.info("令牌校验失败");
            return false;
        }
        try {
            // 校验JWT信息
            Claims claims = JwtUtils.parseJWT(token);

            // 从 Token 中获取用户 ID 和角色
            Long userId = Long.valueOf(claims.get("id").toString());
            int role = Integer.parseInt(claims.get("role").toString()); // 从 Token 中获取角色信息

            //保存用户ID和角色信息到ThreadLocal中
            BaseContext.setCurrentId(userId);
            BaseContext.setCurrentRole(role);

            if (request.getRequestURI().startsWith("/admin")) {
                // 只有角色为1才能访问用户管理接口
                if (role != 1) {
                    response.setStatus(403); // 禁止访问
                    return false;
                }
            }
            return true;

        } catch (Exception e) {
            log.info("令牌校验失败");
            response.setStatus(401);
            response.getWriter().write("令牌校验失败");
            return false;
        }
    }
}